package com.uuj.dome.util;

import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * ClassName:Inquirer
 * PACKAGE_NAME:com.uuj.dome.util
 */
public class Inquirer {

    private List<BooleanExpression> expressions;

    public Inquirer() {
        expressions = new ArrayList<>();
    }

    /**
     * 添加查询条件到query内的查询集合中
     *
     * @param expression 查询条件继承BooleanExpression抽象对象的具体实体对象，queryDSL已封装
     * @return
     */
    public Inquirer putExpression(BooleanExpression expression) {
        expressions.add(expression);
        return this;
    }

    public Predicate buidleQuery() {
        BooleanExpression expression = null;
        for (int i = 0; i < expressions.size(); i++) {
            if (i == 0) {
                expression = expressions.get(i);
            } else {
                expression = expression.and(expressions.get(i));
            }
        }

        return expression;
    }

    /**
     * Iterable 集合转换成 list集合
     *
     * @param iterable 数据源集合
     * @param <T>      类型
     * @return 返回数据list集合
     */
    public <T> List<T> iteratorToList(Iterable<T> iterable) {
        ArrayList<T> list = new ArrayList<>();
        Iterator<T> iterator = iterable.iterator();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }

}
